package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author YYP
 * @date 2020/12/29
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecParamService specParamService;

    /**
     * 根据分类id查询规格组及组内参数
     * @param categoryId
     * @return
     */
    @Override
    public List<SpecGroupDTO> listGroupParamsByCategoryId(Long categoryId) {
        //1.根据分类id，查询规格组
        List<SpecGroup> specGroupList = this.query().eq("category_id", categoryId).list();
        //2.转换为DTO
        List<SpecGroupDTO> specGroupDTOList = SpecGroupDTO.convertEntityList(specGroupList);
        if(CollectionUtils.isEmpty(specGroupDTOList)){
            throw new LyException(404, "该分类下的规格组不存在！");
        }

        for (SpecGroupDTO specGroupDTO : specGroupDTOList) {

            //3.根据规格组id，查询组内规格参数
            List<SpecParam> specParamList = specParamService.query().eq("group_id", specGroupDTO.getId()).list();
            //4.将组内规格参数添加到规格组DTO中
            specGroupDTO.setParams(SpecParamDTO.convertEntityList(specParamList));
        }

        return specGroupDTOList;
    }

    /**
     * 修改规格组
     * @param specGroupDTO
     */
    @Override
    @Transactional
    public void updateSpecGroup(SpecGroupDTO specGroupDTO) {
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        boolean b = this.updateById(specGroup);
        if (!b) {
            throw new LyException(400,"更新失败");
        }
    }

    /**
     * 新增规格组
     * @param specGroupDTO
     */
    @Override
    @Transactional
    public void addSpecGroup(SpecGroupDTO specGroupDTO) {
        //1.新增规格组
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        boolean save = this.save(specGroup);
        if (!save) {
            throw new LyException(400,"添加失败");
        }
    }

    /**
     * 根据商品分类id，查询规格组的集合
     * @param categoryId
     * @return
     */
    @Override
    public List<SpecGroupDTO> listGroupByCategoryId(Long categoryId) {
        List<SpecGroup> specGroupList = this.query().eq("category_id", categoryId).list();
        List<SpecGroupDTO> specGroupDTOList = SpecGroupDTO.convertEntityList(specGroupList);
        return specGroupDTOList;
    }
}
